package com.zl.freight.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.WindowManager;

import com.google.android.cameraview.CameraView;
import com.zl.freight.R;
import com.zl.freight.base.BaseActivity;
import com.zl.freight.utils.PermisionUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * @author zhanglei
 * @date 16/12/10
 * 相机Activity
 */
public class CameraActivity extends BaseActivity {

    @BindView(R.id.camera_sv)
    CameraView cameraView;
    private String filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);
        //设置屏幕常亮（禁止锁屏）
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //判断是否有相机和储存权限
        if (!isPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) || !isPermission(Manifest.permission.CAMERA)) {
            showToast("没有相机和储存权限，无法使用相机");
            finish();
            return;
        }

        initListener();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //判断是否有相机和储存权限
        if (!isPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) || !isPermission(Manifest.permission.CAMERA)) {
            new AlertDialog.Builder(mActivity).setMessage("没有相机和储存权限，无法使用相机")
                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PermisionUtils.getAppDetailSettingIntent(mActivity);
                            finish();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).show();
            return;
        }
        filePath = getExternalFilesDir(null).getAbsolutePath();
        cameraView.setFacing(CameraView.FACING_BACK);
        cameraView.start();
    }

    @Override
    protected void onPause() {
        cameraView.stop();
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 初始化监听
     */
    private void initListener() {

        cameraView.addCallback(new CameraView.Callback() {
            @Override
            public void onCameraOpened(CameraView cameraView) {
                super.onCameraOpened(cameraView);
            }

            @Override
            public void onCameraClosed(CameraView cameraView) {
                super.onCameraClosed(cameraView);
            }

            @Override
            public void onPictureTaken(CameraView cameraView, byte[] data) {
                super.onPictureTaken(cameraView, data);
                storagePicture(data);
            }
        });
    }

    /**
     * 保存照片并返回
     *
     * @param data
     */
    private void storagePicture(byte[] data) {
        showDialog("储存照片中...");
        Observable.just(data)
                .map(new Function<byte[], String>() {
                    @Override
                    public String apply(@NonNull byte[] bytes) throws Exception {
                        return storageImageAndStopCamera(bytes);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
                        hideDialog();
                        Intent intent = new Intent();
                        intent.putExtra("path", s);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        hideDialog();
                        showToast("储存失败请重试");
                    }
                });
    }

    /**
     * 储存拍摄的照片并停止相机的运行
     */
    private String storageImageAndStopCamera(byte[] data) {

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        //创建一个文件流将拍的照片存储到本地
        String path = filePath + "/" + System.currentTimeMillis() + ".jpg";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            final Bitmap resource = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (resource == null) {
                showToast("拍照失败");
            }
//            final Matrix matrix = new Matrix();
            //在这里将图片旋转90度，要不图片就是横着的
//            matrix.setRotate(270);
//            final Bitmap bitmap = Bitmap.createBitmap(resource, 0, 0, resource.getWidth(), resource.getHeight(), matrix, true);
            if (resource != null) {
                resource.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return path;
    }


    @OnClick(R.id.camera_km)
    public void onViewClicked() {
        cameraView.takePicture();
    }
}
